package com.wf.smartcomm.server.client.action;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;


import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.aspectj.util.FileUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.cloopen.rest.sdk.CCPRestSDK;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.opensymphony.xwork2.ModelDriven;
import com.wf.smartcomm.server.apns.IApnsService;
import com.wf.smartcomm.server.apns.model.Payload;
import com.wf.smartcomm.server.bean.Advertisement;
import com.wf.smartcomm.server.bean.Announcement;
import com.wf.smartcomm.server.bean.AppFeedback;
import com.wf.smartcomm.server.bean.Bill;
import com.wf.smartcomm.server.bean.Call;
import com.wf.smartcomm.server.bean.Complain;
import com.wf.smartcomm.server.bean.Decorate;
import com.wf.smartcomm.server.bean.Feedback;
import com.wf.smartcomm.server.bean.Guide;
import com.wf.smartcomm.server.bean.House;
import com.wf.smartcomm.server.bean.Image;
import com.wf.smartcomm.server.bean.Message;
import com.wf.smartcomm.server.bean.Praise;
import com.wf.smartcomm.server.bean.Repair;
import com.wf.smartcomm.server.bean.Shop;
import com.wf.smartcomm.server.bean.UnLock;
import com.wf.smartcomm.server.bean.UnLockReport;
import com.wf.smartcomm.server.bean.UnitMachine;
import com.wf.smartcomm.server.bean.User;
import com.wf.smartcomm.server.bean.Version;
import com.wf.smartcomm.server.bean.Village;
import com.wf.smartcomm.server.config.UmConfig;
import com.wf.smartcomm.server.model.AreaModel;
import com.wf.smartcomm.server.model.BanModel;
import com.wf.smartcomm.server.model.CellModel;
import com.wf.smartcomm.server.model.Page;
import com.wf.smartcomm.server.model.PushMessage;
import com.wf.smartcomm.server.model.UnlockCode;
import com.wf.smartcomm.server.push.Pusher;
import com.wf.smartcomm.server.response.ResponseCode;
import com.wf.smartcomm.server.response.ResponseMessage;
import com.wf.smartcomm.server.service.AdService;
import com.wf.smartcomm.server.service.AnnounceService;
import com.wf.smartcomm.server.service.AppFeedbackService;
import com.wf.smartcomm.server.service.BillService;
import com.wf.smartcomm.server.service.CallService;
import com.wf.smartcomm.server.service.ComplainService;
import com.wf.smartcomm.server.service.DecorateService;
import com.wf.smartcomm.server.service.FeedbackService;
import com.wf.smartcomm.server.service.GuideService;
import com.wf.smartcomm.server.service.HouseService;
import com.wf.smartcomm.server.service.ImageService;
import com.wf.smartcomm.server.service.MerchantService;
import com.wf.smartcomm.server.service.MessageService;
import com.wf.smartcomm.server.service.PaymentService;
import com.wf.smartcomm.server.service.PraiseService;
import com.wf.smartcomm.server.service.RepairService;
import com.wf.smartcomm.server.service.ScoreService;
import com.wf.smartcomm.server.service.ShopService;
import com.wf.smartcomm.server.service.UmConfigService;
import com.wf.smartcomm.server.service.UnitMachService;
import com.wf.smartcomm.server.service.UserService;
import com.wf.smartcomm.server.service.VersionService;
import com.wf.smartcomm.server.service.VillageService;
import com.wf.smartcomm.server.service.YellowPageService;
import com.wf.smartcomm.server.util.ConstantUtils;
import com.wf.smartcomm.server.util.IdUtils;
import com.wf.smartcomm.server.util.PushUtils;
import com.wf.smartcomm.server.util.StringUtil;

/** 
 * @author 38884306@qq.com  
 * @version 创建时间：2015-5-19 下午2:15:33 
 * 
 */
@Controller
@Scope("prototype")
public class UserAction extends BaseAction implements ModelDriven<User> {

	private User user = new User();
	
	private static Logger logger = Logger.getLogger(UserAction.class);
	
	@Resource
	private UserService userServiceImpl;
	@Resource
	private ImageService imageServiceImpl;
	@Resource
	private HouseService houseServiceImpl;
	@Resource
	private ComplainService complainServiceImpl;
	@Resource
	private PraiseService praiseServiceImpl;
	@Resource
	private RepairService repairServiceImpl;
	@Resource
	private ShopService shopServiceImpl;
	@Resource
	private DecorateService decorateServiceImpl;
	@Resource
	private PaymentService paymentServiceImpl;
	@Resource
	private UnitMachService unitMachServiceImpl;
	@Resource
	private FeedbackService feedbackServiceImpl;
	@Resource
	private AdService adServiceImpl;
	
	@Resource
	private YellowPageService ypServiceImpl;
	
	@Resource
	private AnnounceService announceServiceImpl;
	
	@Resource
	private GuideService guideServiceImpl;
	
	@Resource
	private VillageService villageServiceImpl;
	
	@Resource
	private UmConfigService umConfigServiceImpl;
	
	@Resource
	private MessageService msgServiceImpl;
	
	@Resource
	private VersionService versionServiceImpl;
	
	@Resource
	private AppFeedbackService appFeedbackService;
	
	@Resource
	private BillService billService;
	
	@Resource
	private CallService callService;
	
	@Resource
	private ScoreService scoreService;
	
	@Resource
	private MerchantService merchantService;
	
	public void get() throws Exception {
		user = userServiceImpl.getUserById(user.getObjectId());
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", user);
		printJsonData(gson.toJson(map));
	}
	
	public void registe() throws Exception{
		HashMap<String, Object> map = new HashMap<String, Object>();
		User exist = userServiceImpl.getUserByUsername(user.getUsername());
		if ( exist != null) {
			if (!StringUtil.isEmpty(exist.getOpenId())) {
				map.put("code", ResponseCode.USER_ALREADY_EXIST_WEIXIN);
				map.put("data", ResponseMessage.USERNAME_ALREADY_EXIST);
			}else {
				map.put("code", ResponseCode.USERNAME_ALREADY_EXIST);
				map.put("data", ResponseMessage.USERNAME_ALREADY_EXIST);
			}
		} else {
			user.setPassword(IdUtils.MD5(user.getPassword()));
			if (!StringUtil.isEmpty(user.getId())) { //兼容老版本
				user.setId(IdUtils.MD5(user.getId()));
			}
			user.setUserType(ConstantUtils.USER_TYPE_APP);
			user.setObjectId(IdUtils.uuid());
			user.setPushId(IdUtils.uuid16());
			user.setCreatedAt(String.valueOf(System.currentTimeMillis()));
			user.setUpdateAt(user.getCreatedAt());
			user.setIsUnReg("0");
			user.setDeviceType(ConstantUtils.DEVICE_TYPE_UNKNOW);
			user.setType(ConstantUtils.USER_TYPE_UNKNOW);
			userServiceImpl.registe(user);
			HashMap<String, Object> result = null;
			CCPRestSDK restAPI = new CCPRestSDK();
			if (PushUtils.isDevEnv) {
				restAPI.init("sandboxapp.cloopen.com", "8883");
				restAPI.setAccount("8a48b551516c09cd01516c36b1cf00dd", "a989200a4e29483cb3e5d6107ae9fdd0");
				restAPI.setAppId("aaf98f89516bf50b015180a2d42a2875");
			} else {
				restAPI.init(PushUtils.pushConfig.getProperty("CloudAddress"), PushUtils.pushConfig.getProperty("CloudPort"));// 初始化服务器地址和端口，格式如下，服务器地址不需要写https://
				restAPI.setAccount(PushUtils.pushConfig.getProperty("CloudMainAccount"), PushUtils.pushConfig.getProperty("CloudMainToken"));// 初始化主帐号和主帐号TOKEN
				restAPI.setAppId(PushUtils.pushConfig.getProperty("CloudAppId"));// 初始化应用ID
			}
			result = restAPI.createSubAccount(user.getObjectId());
			if("000000".equals(result.get("statusCode"))){
				//正常返回输出data包体信息（map）
				HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
				List<HashMap<String,Object>> object =  (List<HashMap<String,Object>>) data.get("SubAccount");
				for (HashMap<String, Object> hashMap : object) {
					if (hashMap.containsKey("subAccountSid")) {
						user.setSubAccountSid(hashMap.get("subAccountSid").toString());
					}
					if (hashMap.containsKey("voipAccount")) {
						user.setVoipAccount(hashMap.get("voipAccount").toString());
					}
					if (hashMap.containsKey("voipPwd")) {
						user.setVoipPwd(hashMap.get("voipPwd").toString());
					}
					if (hashMap.containsKey("subToken")) {
						user.setSubToken(hashMap.get("subToken").toString());
					}
				}
				userServiceImpl.initVoipInfo(user);
				map.put("code", ResponseCode.OK);
				map.put("data", user);
			}else{
				//异常返回输出错误码和错误信息
				System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
				map.put("code", result.get("statusCode"));
				map.put("data", result.get("statusMsg"));
				userServiceImpl.realDel(user);
			}
			
		}

		printJsonData(gson.toJson(map));
	}
	
	public void login() throws Exception {
		HashMap<String, Object> map = new HashMap<String, Object>();
		user.setPassword(IdUtils.MD5(user.getPassword()));
		User exist = userServiceImpl.login(user);
		if (exist != null) {
			String deviceType = request.getParameter("deviceType");
			String appleToken = request.getParameter("appleToken");
			String deviceToken = request.getParameter("deviceToken");
			logger.info("old token:---->" + exist.getDeviceToken());
			logger.info("new token:---->" +deviceToken);
			if (StringUtils.isNotEmpty(exist.getDeviceToken()) && !exist.getDeviceToken().equals(deviceToken)) {
				if (exist.getDeviceType().equals(ConstantUtils.DEVICE_TYPE_ANDROID)) {
					Pusher pusher = PushUtils.getClientPusher();
					PushMessage pmsg = new PushMessage();
					pmsg.setPushType(ConstantUtils.PUSH_TYPE_OFFLINE);
					pusher.push0x20Message(exist.getPushId().getBytes(), gson.toJson(pmsg).getBytes());
					pusher.close();
					exist.setPushId(IdUtils.uuid16());
				} else if(exist.getDeviceType().equals(ConstantUtils.DEVICE_TYPE_APPLE)){
					IApnsService service = PushUtils.getApnsService();
					Payload payload = new Payload();
					payload.setAlert("您的账号在另外一台设备登录！");
					payload.setBadge(0);
					payload.setSound("default");
					payload.addParam("type", ConstantUtils.PUSH_TYPE_OFFLINE);
					service.sendNotification(exist.getAppleToken(), payload);
				}
			}
			if (StringUtil.isEmpty(deviceType)) {
				deviceType = ConstantUtils.DEVICE_TYPE_ANDROID;
				appleToken = "";
			}
			exist.setDeviceType(deviceType);
			exist.setAppleToken(appleToken);
			exist.setDeviceToken(deviceToken);
			userServiceImpl.update(exist);
			map.put("code", ResponseCode.OK);
			map.put("data",exist);
		}else {
			map.put("code", ResponseCode.USERNAME_OR_PASSWORD_WRONG);
			map.put("data", ResponseMessage.USERNAME_OR_PASSWORD_WRONG);
		}

		printJsonData(gson.toJson(map));
	}
	
	public void logout() throws Exception {
		HashMap<String, Object> map = new HashMap<String, Object>();
		user = userServiceImpl.getUserById(user.getObjectId());
		user.setDeviceType(ConstantUtils.DEVICE_TYPE_UNKNOW);
		userServiceImpl.logout(user);
		map.put("code", ResponseCode.OK);
		printJsonData(gson.toJson(map));
	}
	
	public void modifyPassword() throws Exception {
		HashMap<String, Object> map = new HashMap<String, Object>();
		String oldPwd = request.getParameter("oldPwd");
		String newPwd = request.getParameter("newPwd");
		user = userServiceImpl.getUserById(user.getObjectId());
		if (!user.getPassword().equals(IdUtils.MD5(oldPwd))) {
			map.put("code", ResponseCode.OLD_PASSWORD_WRONG);
			map.put("data", ResponseMessage.OLD_PASSWORD_WRONG);
			printJsonData(gson.toJson(map));
			return;
		}
		user.setPassword(IdUtils.MD5(newPwd));
		userServiceImpl.updateInfo(user);
		map.put("code", ResponseCode.OK);
		printJsonData(gson.toJson(map));
	}
	
	public void forgotPassword() throws Exception {
		HashMap<String, Object> map = new HashMap<String, Object>();
		String password = request.getParameter("newPassword");
		user = userServiceImpl.getUserByUsername(user.getUsername());
		if (user == null) {
			map.put("code", ResponseCode.USER_NOT_EXIST);
			map.put("data", ResponseMessage.USER_NOT_EXIST);
			printJsonData(gson.toJson(map));
			return;
		}
		user.setPassword(IdUtils.MD5(password));
		userServiceImpl.update(user);
		map.put("code", ResponseCode.OK);
		printJsonData(gson.toJson(map));
	}
	
	public void searchVillage() throws Exception {
		HashMap<String, Object> map = new HashMap<String, Object>();
		String key = request.getParameter("key");
		villageServiceImpl.queryByKey(key, page);
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void updateInfo() throws Exception {
		User sourceUser = userServiceImpl.getUserById(user.getObjectId());
		sourceUser.updateInfo(user);
		userServiceImpl.updateInfo(sourceUser);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", sourceUser);
		printJsonData(gson.toJson(map));
	}
	
	public void unlock() throws Exception {
		HashMap<String, Object> map = new HashMap<String, Object>();
		Pusher pusher = PushUtils.getInstance();
		PushMessage pMsg = new PushMessage();
		pMsg.setPushType(ConstantUtils.PUSH_TYPE_UNLOCK_MSG);
		UnLockReport unLockReport = new UnLockReport();
		unLockReport.setUserId(user.getObjectId());
		String muid = request.getParameter("muid");
		UnitMachine unitMachine = unitMachServiceImpl.getByUser(new User(muid));
		unLockReport.setType(0);
		unLockReport.setUmId(unitMachine.getObjectId());
		pMsg.setData(unLockReport);
		boolean result = pusher.push0x20Message(unitMachine.getPushId().getBytes(), new Gson().toJson(pMsg).getBytes());
		pusher.close();
		if (result) {
			UnLock unlock = new UnLock();
			unlock.setUser(user);
			unlock.setUnitMachine(unitMachine);
			unlock.setType(ConstantUtils.UNLOCK_TYPE_DEFAULT);
			userServiceImpl.unlock(unlock);
			map.put("code", ResponseCode.OK);
		}else {
			map.put("code", ResponseCode.UNLOCK_FAIL);
		}
		
		printJsonData(gson.toJson(map));
	}
	
	public void centerUnlock()throws Exception{
		Pusher pusher = PushUtils.getInstance();
		PushMessage pMsg = new PushMessage();
		pMsg.setPushType(ConstantUtils.PUSH_TYPE_UNLOCK_MSG);
		String mid = request.getParameter("mid");
		UnitMachine um = unitMachServiceImpl.getById(mid);
		boolean result = pusher.push0x20Message(um.getPushId().getBytes(), gson.toJson(pMsg).getBytes());
		pusher.close();
		if (result) {
			UnLock unlock = new UnLock();
			unlock.setUnitMachine(um);
			unlock.setType(ConstantUtils.UNLOCK_TYPE_CENTERMACHINE);
			userServiceImpl.unlock(unlock);
		}
		printJsonData(200);
	}
	
	public void centerRestart()throws Exception{
		Pusher pusher = PushUtils.getInstance();
		PushMessage pMsg = new PushMessage();
		pMsg.setPushType(ConstantUtils.PUSH_TYPE_RESTART_MSG);
		String mid = request.getParameter("mid");
		UnitMachine um = unitMachServiceImpl.getById(mid);
		boolean result = pusher.push0x20Message(um.getPushId().getBytes(), gson.toJson(pMsg).getBytes());
		pusher.close();
		if (result) {
			UnLock unlock = new UnLock();
			unlock.setUnitMachine(um);
			unlock.setType(ConstantUtils.UNLOCK_TYPE_CENTERMACHINE);
			userServiceImpl.unlock(unlock);
		}
		printJsonData(200);
	}
	
	public void centerReset()throws Exception{
		Pusher pusher = PushUtils.getInstance();
		PushMessage pMsg = new PushMessage();
		pMsg.setPushType(ConstantUtils.PUSH_TYPE_RESET_MSG);
		String mid = request.getParameter("mid");
		UnitMachine um = unitMachServiceImpl.getById(mid);
		boolean result = pusher.push0x20Message(um.getPushId().getBytes(), gson.toJson(pMsg).getBytes());
		pusher.close();
		if (result) {
			UnLock unlock = new UnLock();
			unlock.setUnitMachine(um);
			unlock.setType(ConstantUtils.UNLOCK_TYPE_CENTERMACHINE);
			userServiceImpl.unlock(unlock);
		}
		printJsonData(200);
	}
	
	public void saveComplain() throws Exception {
		Complain complain = new Complain();
		complain.setUser(user);
		complain.setSubject(request.getParameter("subject"));
		complain.setContent(request.getParameter("content"));
		complain.setStatus(ConstantUtils.COMPLAIN_STATUS_PUBLISH);
		complainServiceImpl.save(complain);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", complain);
		printJsonData(gson.toJson(map));
	}
	
	public void saveAppFeedback()throws Exception{
		AppFeedback feedback = new AppFeedback();
		feedback.setUser(user);
		feedback.setCreatedAt(String.valueOf(System.currentTimeMillis()));
		feedback.setObjectId(IdUtils.uuid());
		feedback.setContent(request.getParameter("content"));
		appFeedbackService.save(feedback);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", feedback);
		printJsonData(gson.toJson(map));
	}
	
	public void savePraise() throws Exception {
		Praise praise = new Praise();
		praise.setUser(user);
		praise.setSubject(request.getParameter("subject"));
		praise.setContent(request.getParameter("content"));
		praiseServiceImpl.save(praise);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", praise);
		printJsonData(gson.toJson(map));
	}
	
	
	public void saveUnLock() throws Exception {
		String mid = request.getParameter("mid");
		UnitMachine um = unitMachServiceImpl.getById(mid);
		UnLock unlock = new UnLock();
		unlock.setUnitMachine(um);
		unlock.setType(ConstantUtils.UNLOCK_TYPE_UNITPWD);
		userServiceImpl.unlock(unlock);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		printJsonData(gson.toJson(map));
	}
	
	public void getHouseByNumber() {
		String number = request.getParameter("number");
		UnitMachine um = unitMachServiceImpl.getByUser(user);
		House house = houseServiceImpl.getByUmInfo(um, number);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", house);
	}
	
	public void getUnlocker() throws Exception {
		String number = request.getParameter("number");
		UnitMachine um = unitMachServiceImpl.getByUser(user);
		House house = houseServiceImpl.getByUmInfo(um, number);
		List<User> users = new ArrayList<User>();
		HashMap<String, Object> map = new HashMap<String, Object>();
		if (house != null) {
			users = houseServiceImpl.listUnlocker(house);
			if (StringUtils.isNotEmpty(house.getReceiver()) && house.getReceiver().equals("1")) {
				users = new ArrayList<User>();
			}
			map.put("code", ResponseCode.OK);
			map.put("data", users);
		}else {
			map.put("code", ResponseCode.HOUSE_NOT_EXIST);
			map.put("data", ResponseMessage.HOUSE_NOT_EXIST);
		}
		
		printJsonData(gson.toJson(map));
	}
	
	public void getUnlockerByInfo()throws Exception{
		String vid = request.getParameter("vid");
		String region = request.getParameter("region");
		String building = request.getParameter("building");
		String entrance = request.getParameter("entrance");
		String number = request.getParameter("number");
		House house = houseServiceImpl.getHouseByInfo(vid,region,building,entrance,number);
		List<User> users = new ArrayList<User>();
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		if (house != null) {
			users = houseServiceImpl.listUnlocker(house);
		}
		map.put("data", users);
		printJsonData(gson.toJson(map));
	}
	
	public void getHouseByInfo()throws Exception{
		String vid = request.getParameter("vid");
		String region = request.getParameter("region");
		String building = request.getParameter("building");
		String entrance = request.getParameter("entrance");
		String number = request.getParameter("number");
		House house = houseServiceImpl.getHouseByInfo(vid,region,building,entrance,number);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", house);
		printJsonData(gson.toJson(map));
	}
	
	public void saveRepair() throws Exception {
		String houseId = request.getParameter("houseId");
		House house = new House();
		house.setObjectId(houseId);
		Repair repair = new Repair();
		repair.setUser(user);
		repair.setDescription(request.getParameter("description"));
		repair.setContent(request.getParameter("content"));
		repair.setType(Integer.parseInt(request.getParameter("type")));
		repair.setStartAt(request.getParameter("startAt"));
		repair.setEndAt(request.getParameter("endAt"));
		repair.setStatus(ConstantUtils.REPAIR_STATUS_PUBLISH);
		repair.setHouse(house);
		repairServiceImpl.save(repair);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", repair);
		printJsonData(gson.toJson(map));
	}
	
	public void saveFeedback() throws Exception {
		String repairId = request.getParameter("repairId");
		repairServiceImpl.endRepair(repairId);
		Repair repair = new Repair();
		repair.setObjectId(repairId);
		Feedback feedback = new Feedback();
		feedback.setUser(user);
		feedback.setRepair(repair);
		feedback.setContent(request.getParameter("content"));
		feedbackServiceImpl.save(feedback);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", feedback);
		printJsonData(gson.toJson(map));
	}
	
	public void getRepair() throws Exception {
		String repairId = request.getParameter("oId");
		Repair repair = repairServiceImpl.getById(repairId);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", repair);
		printJsonData(gson.toJson(map));
	}
	
	public void getBill() throws Exception {
		String billId = request.getParameter("oId");
		Bill bill = billService.get(billId);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", bill);
		printJsonData(gson.toJson(map));
	}
	
	public void getAdvertisement() throws Exception {
		String aId = request.getParameter("oId");
		Advertisement ad = adServiceImpl.get(aId);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", ad);
		printJsonData(gson.toJson(map));
	}
	
	public void getAnnouncement() throws Exception {
		String id = request.getParameter("oId");
		Announcement announce = announceServiceImpl.get(id);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", announce);
		printJsonData(gson.toJson(map));
	}
	
	public void getSetting() throws Exception {
		String id = request.getParameter("oId");
		UmConfig config = umConfigServiceImpl.get(id);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", config);
		printJsonData(gson.toJson(map));
	}
	
	public void getMessage() throws Exception {
		String id = request.getParameter("oId");
		Message msg = msgServiceImpl.get(id);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", msg);
		printJsonData(gson.toJson(map));
	}
	
	public void saveDecorate() throws Exception {
		Decorate decorate = new Decorate();
		decorate.setUser(user);
		decorate.setCompany(request.getParameter("company"));
		decorate.setPmName(request.getParameter("pmName"));
		decorate.setPmNumber(request.getParameter("pmNumber"));
		decorate.setStatus(ConstantUtils.DECORATE_STATUS_UNCHECK);
		decorate.setStartAt(request.getParameter("startAt"));
		decorate.setEndAt(request.getParameter("endAt"));
		decorate.setRemark(request.getParameter("remark"));
		House house = new House();
		house.setObjectId(request.getParameter("houseId"));
		decorate.setHouse(house);
		decorateServiceImpl.save(decorate);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", decorate);
		printJsonData(gson.toJson(map));
	}
	
	public void delAttach() throws Exception {
		String attachId = request.getParameter("attachId");
		User attachUser = userServiceImpl.getUserById(attachId);
		attachUser.setIsUnReg("1");
		userServiceImpl.updateInfo(attachUser);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		printJsonData(gson.toJson(map));
	}
	
	public void setAvatar() throws Exception {
		boolean isModify = true;
		Image image = new Image();
		user = userServiceImpl.getUserById(user.getObjectId());
		if (StringUtil.isEmpty(user.getAvatar())) {
			image.setObjectId(IdUtils.uuid());
			image.setUser(user);
			isModify = false;
		}else {
			 image = imageServiceImpl.getAvatar(user);
		}
		
		MultiPartRequestWrapper pr = (MultiPartRequestWrapper) request;
		File[] files = pr.getFiles("fileData");
		if (files != null) {
			File file = files[0];
			String fileName = IdUtils.uuid()+".png";
			String path = request.getServletContext().getRealPath(
					"images");
			image.setFileName(fileName);
			String requestUrl = request.getRequestURL().toString();
			String url = requestUrl.substring(0, requestUrl.lastIndexOf("wisdomhome"))+"images/"+fileName;
			//String url = PushUtils.pushConfig.getProperty("BaseImageUrl") + fileName;
			image.setUrl(url);
			user.setAvatar(url);
			File des = new File(path + File.separator + fileName);
			FileUtil.copyFile(file, des);
		}
		
		if (isModify) {
			imageServiceImpl.update(image);
		}else {
			imageServiceImpl.save(image);
		}
		userServiceImpl.updateInfo(user);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", image);
		printJsonData(gson.toJson(map));
	}
	
	public void test()throws Exception{
		String vid = request.getParameter("vid");
		List<House> houses = houseServiceImpl.listToJobSchedule(new Village(vid));
		HashMap<String,Object> map = new HashMap<String,Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", houses);
		printJsonData(gson.toJson(map));
	}
	
/*     */   public void selectHouse() throws Exception {
/* 419 */     HashMap<String,Object> map = new HashMap<String,Object>();
/* 420 */     String hid = request.getParameter("hid");
/* 421 */     House house = houseServiceImpl.getById(hid);
/* 422 */     if (house.getUser() != null) {
/* 423 */       map.put("code", ResponseCode.HOUSE_ALREADY_BIND);
/* 424 */       map.put("data", "house already bind");
/* 425 */       printJsonData(gson.toJson(map));
/* 426 */       return;
/*     */     }
/* 428 */     user = userServiceImpl.getUserById(user.getObjectId());
/* 429 */     if (house.getId().equals(user.getId()))
/*     */     {
/* 431 */       user.setType(ConstantUtils.USER_TYPE_PRIMARY);

				if (user.getLoginVillage() == null) {
					user.setLoginVillage(house.getVillage());
				}else if (!user.getLoginVillage().getObjectId().equals(house.getVillage().getObjectId())) {
/* 435 */         userServiceImpl.addVillage(user, house.getVillage());
/*     */       }
				
/* 438 */       userServiceImpl.update(user);
/* 439 */       house.setUser(user);
/* 440 */       house.setVoipPhoneNumber(user.getUsername());
/* 441 */       houseServiceImpl.update(house);
/* 442 */       houseServiceImpl.addUser(hid, user.getObjectId());
/* 443 */       map.put("code", ResponseCode.OK);
/*     */     } else {
/* 445 */       map.put("code", ResponseCode.HOUSE_VALIDATE_FAIL);
/* 446 */       map.put("data", "house validate fail");
/*     */     }
/* 448 */     printJsonData(gson.toJson(map));
/*     */   }
	
	public void listAttachUsers() throws Exception {
		String hid = request.getParameter("hid");
		userServiceImpl.listAttachByHouse(hid,page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void searchUser() throws Exception{
		String key = request.getParameter("key");
		userServiceImpl.searchByKey(key,page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void setPriority() throws Exception{
		HashMap<String, Object> map = new HashMap<String, Object>();
		String userId = request.getParameter("userId");
		String priority = request.getParameter("priority");
		user = userServiceImpl.getUserById(userId);
		user.setPriority(priority);
		userServiceImpl.update(user);
		map.put("code", ResponseCode.OK);
		printJsonData(gson.toJson(map));
	}
	
	public void setVoipNumber() throws Exception{
		HashMap<String, Object> map = new HashMap<String, Object>();
		String hid = request.getParameter("hid");
		String voipNumber = request.getParameter("voipNumber");
		House house = houseServiceImpl.getById(hid);
		house.setVoipPhoneNumber(voipNumber);
		houseServiceImpl.update(house);
		map.put("code", ResponseCode.OK);
		printJsonData(gson.toJson(map));
	}
	
	public void addAttach() throws Exception{
		HashMap<String, Object> map = new HashMap<String, Object>();
		String hid = request.getParameter("hid");
		String hostId = request.getParameter("hostId");
		String attachId = request.getParameter("attachId");
		User attach = userServiceImpl.getUserById(attachId);
		House house = houseServiceImpl.getById(hid);
		if (!hostId.equals(attach.getObjectId())) {
			attach.setType(ConstantUtils.USER_TYPE_ATTACH);
			attach.setParent(new User(hostId));
			attach.setLoginVillage(house.getVillage());
			userServiceImpl.update(attach);
			houseServiceImpl.addUser(hid, attachId);
			map.put("code", ResponseCode.OK);
		}else {
			map.put("code", 205);
		}
		
		printJsonData(gson.toJson(map));
	}
	
	public void newAddAttach() throws Exception{
		HashMap<String, Object> map = new HashMap<String, Object>();
		String hid = request.getParameter("hid");
		String hostId = request.getParameter("hostId");
		String attachNumber = request.getParameter("attachNumber");
		User attach = userServiceImpl.getUserByUsername(attachNumber);
		House house = houseServiceImpl.getById(hid);
		if (attach != null) {
			if (attach.getType().equals(ConstantUtils.USER_TYPE_UNKNOW)) {
				attach.setParent(new User(hostId));
				attach.setLoginVillage(house.getVillage());
				attach.setType(ConstantUtils.USER_TYPE_ATTACH);
				userServiceImpl.update(attach);
				houseServiceImpl.addUser(hid, attach.getObjectId());
				map.put("code", ResponseCode.OK);
			}else {
				map.put("code", ResponseCode.USERNAME_ALREADY_EXIST);
				map.put("data", ResponseMessage.USERNAME_ALREADY_EXIST);
			}
		}else{
			attach = new User();
			attach.setUsername(attachNumber);
			attach.setPassword(IdUtils.MD5("123456"));
			attach.setUserType(ConstantUtils.USER_TYPE_APP);
			attach.setObjectId(IdUtils.uuid());
			attach.setPushId(IdUtils.uuid16());
			attach.setCreatedAt(String.valueOf(System.currentTimeMillis()));
			attach.setUpdateAt(attach.getCreatedAt());
			attach.setIsUnReg("0");
			attach.setDeviceType(ConstantUtils.DEVICE_TYPE_UNKNOW);
			attach.setType(ConstantUtils.USER_TYPE_ATTACH);
			attach.setLoginVillage(house.getVillage());
			attach.setParent(new User(hostId));
			HashMap<String, Object> result = null;
			CCPRestSDK restAPI = new CCPRestSDK();
			if (PushUtils.isDevEnv) {
				restAPI.init("sandboxapp.cloopen.com", "8883");
				restAPI.setAccount("8a48b551516c09cd01516c36b1cf00dd", "a989200a4e29483cb3e5d6107ae9fdd0");
				restAPI.setAppId("aaf98f89516bf50b015180a2d42a2875");
			} else {
				restAPI.init(PushUtils.pushConfig.getProperty("CloudAddress"), PushUtils.pushConfig.getProperty("CloudPort"));// 初始化服务器地址和端口，格式如下，服务器地址不需要写https://
				restAPI.setAccount(PushUtils.pushConfig.getProperty("CloudMainAccount"), PushUtils.pushConfig.getProperty("CloudMainToken"));// 初始化主帐号和主帐号TOKEN
				restAPI.setAppId(PushUtils.pushConfig.getProperty("CloudAppId"));// 初始化应用ID
			}
			result = restAPI.createSubAccount(attach.getObjectId());
			if("000000".equals(result.get("statusCode"))){
				//正常返回输出data包体信息（map）
				HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
				List<HashMap<String,Object>> object =  (List<HashMap<String,Object>>) data.get("SubAccount");
				for (HashMap<String, Object> hashMap : object) {
					if (hashMap.containsKey("subAccountSid")) {
						attach.setSubAccountSid(hashMap.get("subAccountSid").toString());
					}
					if (hashMap.containsKey("voipAccount")) {
						attach.setVoipAccount(hashMap.get("voipAccount").toString());
					}
					if (hashMap.containsKey("voipPwd")) {
						attach.setVoipPwd(hashMap.get("voipPwd").toString());
					}
					if (hashMap.containsKey("subToken")) {
						attach.setSubToken(hashMap.get("subToken").toString());
					}
				}
			}
			userServiceImpl.registe(attach);
			houseServiceImpl.addUser(hid, attach.getObjectId());
			map.put("code", ResponseCode.OK);
		}
		printJsonData(gson.toJson(map));
	}
	
	public void removeAttach() throws Exception{
		HashMap<String, Object> map = new HashMap<String, Object>();
		String attachId = request.getParameter("attachId");
		String hid = request.getParameter("hid");
		User attach = userServiceImpl.getUserById(attachId);
		attach.setParent(null);
		attach.setType(ConstantUtils.USER_TYPE_UNKNOW);
		userServiceImpl.update(attach);
		houseServiceImpl.deleteUser(hid, attachId);
		map.put("code", ResponseCode.OK);
		printJsonData(gson.toJson(map));
	}
	
	public void listHouses() throws Exception {
		user = userServiceImpl.getUserById(user.getObjectId());
		if (user.getType().equals(ConstantUtils.USER_TYPE_ATTACH)) {
			houseServiceImpl.listUnlockHouses(user,page);
		}else {
			houseServiceImpl.listByUser(user,page);
		}
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void getHouse() throws Exception{
		House house = houseServiceImpl.getById(request.getParameter("oId"));
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", house);
		printJsonData(gson.toJson(map));
	}
	
	public void listFeedbacks() throws Exception{
		String repairId = request.getParameter("repairId");
		String complainId = request.getParameter("complainId");
		if (!StringUtil.isEmpty(repairId)) {
			Repair repair = new Repair();
			repair.setObjectId(repairId);
			feedbackServiceImpl.listByRepair(repair, page);
		} else {
			Complain complain = new Complain();
			complain.setObjectId(complainId);
			feedbackServiceImpl.listByComplain(complain, page);
		}
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void listComplains() throws Exception {
		complainServiceImpl.listByUser(user,page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void listPraises() throws Exception {
		praiseServiceImpl.listByUser(user,page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void listRepairs() throws Exception {
		String houseId = request.getParameter("houseId");
		repairServiceImpl.listByHouse(new House(houseId),page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void listBills()throws Exception{
		String houseId = request.getParameter("houseId");
		billService.listByHouse(new House(houseId),page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void listDecorates() throws Exception {
		String houseId = request.getParameter("houseId");
		decorateServiceImpl.listByHouse(new House(houseId),page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void lsitPayments() throws Exception {
		paymentServiceImpl.listByUser(user,page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void listGuides() throws Exception{
		user = userServiceImpl.getUserById(user.getObjectId());
		guideServiceImpl.listByVillage(user.getLoginVillage(), page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void listShops() throws Exception {
		user = userServiceImpl.getUserById(user.getObjectId());
		shopServiceImpl.listByVillage(user.getLoginVillage(), page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void listAnnouncements() throws Exception {
		user = userServiceImpl.getUserById(user.getObjectId());
		announceServiceImpl.list(user.getLoginVillage(), page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void listYellowPages() throws Exception {
		user = userServiceImpl.getUserById(user.getObjectId());
		ypServiceImpl.listByVillage(user.getLoginVillage(), page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void listMessages() throws Exception {
		msgServiceImpl.listByUser(user, page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void listUnlockHouses() throws Exception{
		//user = userServiceImpl.getUserById(user.getObjectId());
		houseServiceImpl.listUnlockHouses(user,page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void getUnlockUser() throws Exception {
		String hid = request.getParameter("hid");
		userServiceImpl.listByHouse(hid,page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void listCity() throws Exception{
		villageServiceImpl.listCity(page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void listVillage() throws Exception{
		String city = request.getParameter("city");
		villageServiceImpl.listByCity(city, page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void setVillage() throws Exception{
		String vid = request.getParameter("vid");
		userServiceImpl.setVillage(user,vid);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		printJsonData(gson.toJson(map));
	}
	
	public void listRegion() throws Exception{
		String vid = request.getParameter("vid");
		Village village = new Village();
		village.setObjectId(vid);
		houseServiceImpl.listRegion(village, page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void listBuilding() throws Exception{
		String vid = request.getParameter("vid");
		String region = request.getParameter("region");
		houseServiceImpl.listBuilding(vid,region, page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void setUmPassword() throws Exception{
		String hid = request.getParameter("hid");
		String umpwd = request.getParameter("umpwd");
		House house = houseServiceImpl.getById(hid);
		house.setUnitPassword(umpwd);
		houseServiceImpl.update(house);
		UnlockCode code = new UnlockCode();
		code.setId(hid);
		code.setCode(umpwd);
		Pusher pusher = PushUtils.getInstance();
		PushMessage msg = new PushMessage();
		msg.setPushType(ConstantUtils.PUSH_TYPE_SET_UMPWD);
		msg.setData(code);
		unitMachServiceImpl.listByHid(hid, page);
		List<UnitMachine> ums = (List<UnitMachine>) page.getDataList();
		for (UnitMachine um : ums) {
			pusher.push0x20Message(um.getPushId().getBytes(), gson.toJson(msg).getBytes());
		}
		pusher.close();
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		printJsonData(gson.toJson(map));
	}
	
	public void listEntrance() throws Exception{
		String vid = request.getParameter("vid");
		String building = request.getParameter("building");
		String region = request.getParameter("region");
		houseServiceImpl.listEntrance(vid, region,building, page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void listHouseByInfo() throws Exception{
		String vid = request.getParameter("vid");
		String region = request.getParameter("region");
		String building = request.getParameter("building");
		String entrance = request.getParameter("entrance");
		Village village = new Village();
		village.setObjectId(vid);
		houseServiceImpl.listBySelect(village,region, building, entrance, page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void listUnitMachines() throws Exception{
		String hid = request.getParameter("houseId");
		House house = houseServiceImpl.getById(hid);
		unitMachServiceImpl.listByHouse(house, page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void setReceiver() throws Exception{
		String houseId = request.getParameter("houseId");
		houseServiceImpl.setReceiver(houseId, "1");
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		printJsonData(gson.toJson(map));
	}
	
	public void resReceiver() throws Exception{
		String houseId = request.getParameter("houseId");
		houseServiceImpl.setReceiver(houseId, "0");
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		printJsonData(gson.toJson(map));
	}
	
	public void getUserByHouse() throws Exception{
		String houseId = request.getParameter("houseId");
		userServiceImpl.listByHouse(houseId, page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void getUmByUser() throws Exception{
		 UnitMachine um = unitMachServiceImpl.getByUser(user);
		 HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("code", ResponseCode.OK);
			map.put("data", um);
			printJsonData(gson.toJson(map));
	}
	
	public void getVersion() throws Exception{
		String oid = request.getParameter("oId");
		Version version = versionServiceImpl.get(oid);
		 HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("code", ResponseCode.OK);
			map.put("data", version);
			printJsonData(gson.toJson(map));
	}
	
	public void setPrioritylist() throws Exception{
		String json = request.getParameter("data");
		List<HashMap<String,String>> list = gson.fromJson(json, new TypeToken<List<HashMap<String,String>>>(){}.getType());
		for (HashMap<String, String> hashMap : list) {
			Entry<String, String> entry = hashMap.entrySet().iterator().next();
			String userId = entry.getKey();
			String priority = entry.getValue();
			user = userServiceImpl.getUserById(userId);
			user.setPriority(priority);
			userServiceImpl.update(user);
		}
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		printJsonData(gson.toJson(map));
	}
	
	public void transferVoip() throws Exception{
		String voipAccount = request.getParameter("voipAccount");
		UnitMachine um = unitMachServiceImpl.getByVoip(voipAccount);
		Pusher pusher = PushUtils.getInstance();
		PushMessage pMsg = new PushMessage();
		pMsg.setPushType(ConstantUtils.PUSH_TYPE_TRANSFER_VOIP);
		boolean result = pusher.push0x20Message(um.getPushId().getBytes(), gson.toJson(pMsg).getBytes());
		pusher.close();
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		if (result) {
			map.put("code", ResponseCode.OK);
		}else {
			map.put("code", ResponseCode.TRANS_VOIP_FAIL);
		}
		printJsonData(gson.toJson(map));
	}
	
	public void getUmByVoipNo() throws IOException{
		String voipAccount = request.getParameter("voipAccount");
		UnitMachine um = unitMachServiceImpl.getByVoip(voipAccount);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", um);
		printJsonData(gson.toJson(map));
	}
	
	public void listGuidesByKey()throws Exception {
		String key = request.getParameter("key");
		user = userServiceImpl.getUserById(user.getObjectId());
		guideServiceImpl.query(user.getLoginVillage(), key,page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void listScores()throws Exception{
		scoreService.list(user, page);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		Gson gson1 = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
				.excludeFieldsWithoutExposeAnnotation().create();
		printJsonData(gson1.toJson(map));
	}
	
	public void getLatestVersion()throws Exception{
		Version version = versionServiceImpl.getLatestVersion(ConstantUtils.APK_TYPE_CLIENT);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", version);
		printJsonData(gson.toJson(map));
	}
	
	public void getLatestAd()throws Exception{
		user = userServiceImpl.getUserById(user.getObjectId());
		Advertisement advertisement = adServiceImpl.getLatestAd(user);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", advertisement);
		printJsonData(gson.toJson(map));
	}
	
	public void listAll()throws Exception{
		String vid = request.getParameter("vid");
		Village village = new Village();
		village.setObjectId(vid);
		houseServiceImpl.listRegion(village, page);
		List<AreaModel> areaModels = new ArrayList<AreaModel>();
		for (Object region : page.getDataList()) {
			AreaModel areaModel = new AreaModel();
			areaModel.setName((String)region);
			Page page1 = new Page();
			List<BanModel> banModels = new ArrayList<BanModel>();
			houseServiceImpl.listBuilding(vid, areaModel.getName(), page1);
			for (Object building : page1.getDataList()) {
				BanModel banModel = new BanModel();
				banModel.setName((String)building);
				Page page2 = new Page();
				houseServiceImpl.listEntrance(vid, areaModel.getName(), banModel.getName(), page2);
				List<CellModel> cellModels = new ArrayList<CellModel>();
				for (Object entrance : page2.getDataList()) {
					CellModel cellModel = new CellModel((String)entrance);
					cellModels.add(cellModel);
				}
				banModel.setCellList(cellModels);
				banModels.add(banModel);
			}
			areaModel.setBanList(banModels);
			areaModels.add(areaModel);
		}
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", areaModels);
		printJsonData(gson.toJson(map));
	}
	
	public void listAllWithNumber()throws Exception{
		String vid = request.getParameter("vid");
		Village village = new Village();
		village.setObjectId(vid);
		houseServiceImpl.listRegion(village, page);
		List<AreaModel> areaModels = new ArrayList<AreaModel>();
		for (Object region : page.getDataList()) {
			AreaModel areaModel = new AreaModel();
			areaModel.setName((String)region);
			Page page1 = new Page();
			List<BanModel> banModels = new ArrayList<BanModel>();
			houseServiceImpl.listBuilding(vid, areaModel.getName(), page1);
			for (Object building : page1.getDataList()) {
				BanModel banModel = new BanModel();
				banModel.setName((String)building);
				Page page2 = new Page();
				houseServiceImpl.listEntrance(vid, areaModel.getName(), banModel.getName(), page2);
				List<CellModel> cellModels = new ArrayList<CellModel>();
				for (Object entrance : page2.getDataList()) {
					CellModel cellModel = new CellModel((String)entrance);
					Page page3 = new Page();
					houseServiceImpl.listAllWithNumber(vid, areaModel.getName(), banModel.getName(), cellModel.getName(), page3);
					cellModel.setInfos(page3.getDataList());
					cellModels.add(cellModel);
				}
				banModel.setCellList(cellModels);
				banModels.add(banModel);
			}
			areaModel.setBanList(banModels);
			areaModels.add(areaModel);
		}
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", areaModels);
		printJsonData(new Gson().toJson(map));
	}
	
	public String showShopDetail() throws Exception{
		String shopId = request.getParameter("shopId");
		Shop shop = shopServiceImpl.get(shopId);
		shop.setSummary(URLDecoder.decode(shop.getSummary(), "UTF-8"));
		request.setAttribute("shop", shop);
		return "shopDetail";
	}
	
	public String showGuideDetail() throws Exception{
		String guideId = request.getParameter("guideId");
		Guide guide = guideServiceImpl.get(guideId);
		guide.setContent(URLDecoder.decode(guide.getContent(), "UTF-8"));
		request.setAttribute("guide", guide);
		return "guideDetail";
	}
	
	public String showAnnounceDetail() throws Exception{
		String announceId = request.getParameter("announceId");
		Announcement announcement = announceServiceImpl.get(announceId);
		announcement.setContent(URLDecoder.decode(announcement.getContent(), "UTF-8"));
		request.setAttribute("announce", announcement);
		return "announceDetail";
	}
	
	public void deleteMsg()throws Exception{
		String messageId = request.getParameter("messageId");
		msgServiceImpl.delete(messageId);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		printJsonData(new Gson().toJson(map));
	}
	
	public void deleteAllMsg() throws Exception{
		msgServiceImpl.deleteAll(user);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		printJsonData(new Gson().toJson(map));
	}
	
	public void readMsg()throws Exception{
		String messageId = request.getParameter("messageId");
		msgServiceImpl.readMsg(messageId);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		printJsonData(new Gson().toJson(map));
	}
	
	public void getCaller()throws Exception{
		HashMap<String, Object> map = new HashMap<String, Object>();
		String called = request.getParameter("called");
		Call call = callService.getCaller(called);
		if (call != null) {
			UnitMachine um = unitMachServiceImpl.getByVoip(call.getCaller());
			map.put("code", ResponseCode.OK);
			map.put("data", um);
			callService.delete(call.getCallId());
		}else {
			map.put("code", 404);
		}
		printJsonData(gson.toJson(map));
	}
	
	public void countUnReadMsg()throws Exception{
		Integer counts = msgServiceImpl.countUnRead(user);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", counts);
		printJsonData(gson.toJson(map));
	}
	
	public void sendHangup()throws Exception{
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		Pusher pusher = PushUtils.getInstance();
		PushMessage pMsg = new PushMessage();
		pMsg.setPushType(ConstantUtils.PUSH_TYPE_HANGUP);
		String mid = request.getParameter("mid");
		UnitMachine um = unitMachServiceImpl.getById(mid);
		pusher.push0x20Message(um.getPushId().getBytes(), gson.toJson(pMsg).getBytes());
		pusher.close();
		printJsonData(gson.toJson(map));
	}
	
	public void listMerchants()throws Exception{
		String type = request.getParameter("type");
		int code = 0;
		if (StringUtils.isNotEmpty(type)) {
			code = Integer.parseInt(request.getParameter("type"));
		}
		page = merchantService.pageList(page,code);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", page.getDataList());
		printJsonData(gson.toJson(map));
	}
	
	public void listMachines()throws Exception{
		String vid = request.getParameter("vid");
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", unitMachServiceImpl.listAllByVillage(new Village(vid)));
		printJsonData(gson.toJson(map));
	}

	@Override
	public User getModel() {
		return user;
	}
}
